package cn.tianyigps.tianyigpselectricfence.dao;

import cn.tianyigps.tianyigpselectricfence.dto.GeoFenccRequestDto;
import cn.tianyigps.tianyigpspublic.bean.EquipmentModel;
import cn.tianyigps.tianyigpspublic.bean.GeoFence;
import cn.tianyigps.tianyigpspublic.param.constant.CollectionNameConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Author: WEI.YUAN
 * @Descirption:
 * @Date: 2019/4/11_11:28
 */
@Repository
public class ElectricFenceDaoImpl implements ElectricFenceDao {
    @Autowired
    MongoTemplate mongoTemplate;


    @Override
    public List<GeoFence> getFenceByLocation(GeoFenccRequestDto geoFenccRequestDto) {
        GeoJsonPoint geoJsonPoint = new GeoJsonPoint(new Point(geoFenccRequestDto.getLongitude(), geoFenccRequestDto.getLatitude()));
        Criteria criteria = new Criteria();
        if (!StringUtils.isEmpty(geoFenccRequestDto.getGroup())) {
            //当围栏组不为空时
            criteria = Criteria.where("polygon").intersects(geoJsonPoint).and("group").is(geoFenccRequestDto.getGroup());
        } else if (!CollectionUtils.isEmpty(geoFenccRequestDto.getFenIdList())) {
            //当围栏集合id不为空时
            criteria = Criteria.where("polygon").intersects(geoJsonPoint).and("id").in(geoFenccRequestDto.getFenIdList());
        } else {
            //当不传围栏信息时全表扫描
            criteria = Criteria.where("polygon").intersects(geoJsonPoint);
        }
        Query query = new Query(criteria);
        return mongoTemplate.find(query, GeoFence.class, CollectionNameConstant.GEO_FENCE);
    }

    @Override
    public EquipmentModel getEQCheckModelById(String id) {
        Query query = new Query(Criteria.where("equipmentId").is(id));
        List<EquipmentModel> eqModels = mongoTemplate.find(query, EquipmentModel.class, CollectionNameConstant.LATEST_EQUIPMENT_DATA);
        EquipmentModel eqmodel = new EquipmentModel();
        if (!CollectionUtils.isEmpty(eqModels)) {
            eqmodel = eqModels.get(0);
        }
        return eqmodel;
    }
}
